package com.sundi.ecsystem.web;


import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sundi.eccommon.vo.ResultEntity;
import com.sundi.ecpaystarter.pay.alibaba.qrcode.service.AlibabapayQrCodeService;
import com.sundi.ecsystem.entity.EcCart;
import com.sundi.ecsystem.service.AlibabaPayService;
import com.sundi.ecsystem.service.IEcCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/alibaba/pay")
@Slf4j
public class AlibabaPayController {

    @Autowired
    AlibabapayQrCodeService alibabapayQrCodeService;

    @Autowired
    AlibabaPayService alibabaPayService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    IEcCartService cartService;

    @RequestMapping("/createPayOrder")
    public ResultEntity createPayOrder(String orderNo,Integer userId) throws AlipayApiException {
        log.info("创建支付宝扫码订单开始订单号为:{}",orderNo);
        log.info("用户id:{}",userId);
        if(redisTemplate.hasKey(orderNo)){
            String qrcode = redisTemplate.opsForValue().get(orderNo);
            log.info("根据orderNo:{}到redis 中查询二维码:{}",orderNo,qrcode);
            return ResultEntity.ok("创建支付宝扫码支付订单成功",qrcode);
        }
        log.info("根据orderNo:{}到redis 中查询二维码不存在开始调用支付宝的接口创建预支付订单......");
        EntityWrapper<EcCart> wrapper = new EntityWrapper<EcCart>();
        wrapper.eq("user_id",userId);
        List<EcCart> ecCarts = cartService.selectList(wrapper);

        log.info("查询到的订单为:{}",ecCarts);
        Map<String,String> map = new HashMap<>();
        String user_id=userId.toString();
        map.put("out_trade_no",orderNo);
        map.put("trade_no",orderNo);
        map.put("total_amount",user_id);
        map.put("subject","Iphone6 16G");
        //商家id
        map.put("store_id","2088102180178941");
        map.put("timeout_express","7200m");
        //map.put("user_id",user_id);
        AlipayTradePrecreateResponse qrCodePayOrder = alibabapayQrCodeService.createQrCodePayOrder(map);
        String qrcode = alibabaPayService.getAlibabaPayQRCode(qrCodePayOrder);
        log.info("创建支付宝扫码订单结束订单号为:{}",orderNo);
        return ResultEntity.ok("创建支付宝扫码支付订单成功",qrcode);
    }
}

